package com.sys.SysFeedingRecords.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.sys.SysFeedingRecords.domain.SysInventory;
import com.sys.SysFeedingRecords.mapper.SysInventoryMapper;
import com.sys.SysTanks.domain.SysTanks;
import com.sys.SysTanks.mapper.SysTanksMapper;
import com.sys.common.core.domain.AjaxResult;
import com.sys.common.utils.DateUtils;
import com.sys.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sys.SysFeedingRecords.mapper.SysFeedingRecordsMapper;
import com.sys.SysFeedingRecords.domain.SysFeedingRecords;
import com.sys.SysFeedingRecords.service.ISysFeedingRecordsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 投喂记录Service业务层处理
 * 
 * @author sys
 * @date 2025-09-04
 */
@Service
public class SysFeedingRecordsServiceImpl implements ISysFeedingRecordsService 
{
    @Autowired
    private SysFeedingRecordsMapper sysFeedingRecordsMapper;
    @Autowired
    private SysTanksMapper sysTanksMapper;
    @Autowired
    private SysInventoryMapper sysInventoryMapper;

    /**
     * 查询投喂记录
     * 
     * @param id 投喂记录主键
     * @return 投喂记录
     */
    @Override
    public SysFeedingRecords selectSysFeedingRecordsById(Long id)
    {
        return sysFeedingRecordsMapper.selectSysFeedingRecordsById(id);
    }

    /**
     * 查询投喂记录列表
     * 
     * @param sysFeedingRecords 投喂记录
     * @return 投喂记录
     */
    @Override
    public List<SysFeedingRecords> selectSysFeedingRecordsList(SysFeedingRecords sysFeedingRecords)
    {
        return sysFeedingRecordsMapper.selectSysFeedingRecordsList(sysFeedingRecords);
    }

    /**
     * 新增投喂记录
     *
     * @param sysFeedingRecords 投喂记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 关键：开启事务
    public AjaxResult insertSysFeedingRecords(SysFeedingRecords sysFeedingRecords)
    {
        Long tankId = sysFeedingRecords.getTankId();
        Long inventoryId = sysFeedingRecords.getInventoryId(); // 新增字段
        BigDecimal amount = sysFeedingRecords.getAmount();

        // 1. 校验养殖桶是否存在
        SysTanks tank = sysTanksMapper.selectSysTanksById(tankId);
        if (tank == null) {
            return AjaxResult.error("养殖桶不存在");
        }

        // 2. 校验库存记录是否存在
        if (inventoryId == null) {
            return AjaxResult.error("请选择使用的物资、批次以及投喂量");
        }
        SysInventory inventory = sysInventoryMapper.selectSysInventoryById(inventoryId);
        if (inventory == null) {
            return AjaxResult.error("物资库存记录不存在");
        }

        // 在新增和修改方法中添加
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            return AjaxResult.error("投喂量必须大于0");
        }

        // 3. 校验库存是否充足
        if (inventory.getCurrentStock().compareTo(amount) < 0) {
            return AjaxResult.error("库存不足！当前库存：" + inventory.getCurrentStock() + inventory.getUnit());
        }
        // 4. 扣减库存
        inventory.setTotalOut(inventory.getTotalOut().add(amount));
        inventory.setCurrentStock(inventory.getCurrentStock().subtract(amount));
        inventory.setUpdateBy(SecurityUtils.getUsername());
        inventory.setUpdateTime(DateUtils.getNowDate());
        int updateRows = sysInventoryMapper.updateSysInventory(inventory);
        if (updateRows <= 0) {
            throw new RuntimeException("更新库存失败");
        }

        // 5. 设置投喂记录信息
        sysFeedingRecords.setCreateTime(DateUtils.getNowDate());
        sysFeedingRecords.setUpdateTime(DateUtils.getNowDate());
        sysFeedingRecords.setCreateBy(SecurityUtils.getUsername());
        sysFeedingRecords.setUpdateBy(SecurityUtils.getUsername());

        // 6. 保存投喂记录
        int insertRows = sysFeedingRecordsMapper.insertSysFeedingRecords(sysFeedingRecords);
        if (insertRows <= 0) {
            throw new RuntimeException("保存投喂记录失败");
        }

        return AjaxResult.success("投喂记录新增成功，库存已扣减");
//        return AjaxResult.success(sysFeedingRecordsMapper.insertSysFeedingRecords(sysFeedingRecords));
    }

    /**
     * 修改投喂记录
     * 
     * @param sysFeedingRecords 投喂记录
     * @return 结果
     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public int updateSysFeedingRecords(SysFeedingRecords sysFeedingRecords)
//    {
//        sysFeedingRecords.setUpdateTime(DateUtils.getNowDate());
//        sysFeedingRecords.setUpdateBy(SecurityUtils.getUsername());
//        return sysFeedingRecordsMapper.updateSysFeedingRecords(sysFeedingRecords);
//    }

    /**
     * 修改投喂记录
     *
     * @param sysFeedingRecords 投喂记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateSysFeedingRecords(SysFeedingRecords sysFeedingRecords) {
        Long id = Long.valueOf(sysFeedingRecords.getId());
        BigDecimal newAmount = sysFeedingRecords.getAmount();
        Long inventoryId = sysFeedingRecords.getInventoryId(); // 使用的库存ID

        // 1. 查询原投喂记录
        SysFeedingRecords oldRecord = sysFeedingRecordsMapper.selectSysFeedingRecordsById(id);
        if (oldRecord == null) {
            return AjaxResult.error("投喂记录不存在");
        }

        // 2. 获取关联的库存记录
        SysInventory inventory = sysInventoryMapper.selectSysInventoryById(inventoryId);
        if (inventory == null) {
            return AjaxResult.error("关联的库存记录不存在");
        }

        BigDecimal oldAmount = oldRecord.getAmount();

        // 3. 如果投喂量未变化，无需处理库存
        if (newAmount.compareTo(oldAmount) == 0) {
            sysFeedingRecords.setUpdateTime(DateUtils.getNowDate());
            sysFeedingRecords.setUpdateBy(SecurityUtils.getUsername());
            sysFeedingRecordsMapper.updateSysFeedingRecords(sysFeedingRecords);
            return AjaxResult.success("投喂记录更新成功（投喂量未变）");
        }

        // 4. 计算差额
        BigDecimal diff = newAmount.subtract(oldAmount); // 正数表示增加投喂，负数表示减少

        // 5. 判断库存是否足够（仅当增加投喂量时）
        if (diff.compareTo(BigDecimal.ZERO) > 0) {
            if (inventory.getCurrentStock().compareTo(diff) < 0) {
                return AjaxResult.error("库存不足！需额外 " + diff + inventory.getUnit() + "，当前剩余 " + inventory.getCurrentStock() + inventory.getUnit());
            }
            // 扣减库存
            inventory.setCurrentStock(inventory.getCurrentStock().subtract(diff));
            inventory.setTotalOut(inventory.getTotalOut().add(diff));
        }
        // 6. 如果投喂量减少，归还库存
        else if (diff.compareTo(BigDecimal.ZERO) < 0) {
            BigDecimal refund = diff.abs();
            inventory.setCurrentStock(inventory.getCurrentStock().add(refund));
            inventory.setTotalOut(inventory.getTotalOut().subtract(refund));
        }

        // 7. 更新库存
        inventory.setUpdateBy(SecurityUtils.getUsername());
        inventory.setUpdateTime(DateUtils.getNowDate());
        int updateInventoryRows = sysInventoryMapper.updateSysInventory(inventory);
        if (updateInventoryRows <= 0) {
            throw new RuntimeException("更新库存失败");
        }

        // 8. 更新投喂记录
        sysFeedingRecords.setUpdateTime(DateUtils.getNowDate());
        sysFeedingRecords.setUpdateBy(SecurityUtils.getUsername());
        int updateFeedingRows = sysFeedingRecordsMapper.updateSysFeedingRecords(sysFeedingRecords);
        if (updateFeedingRows <= 0) {
            throw new RuntimeException("更新投喂记录失败");
        }

        return AjaxResult.success("投喂记录更新成功，库存已同步调整");
    }

    /**
     * 批量删除投喂记录
     * 
     * @param ids 需要删除的投喂记录主键
     * @return 结果
     */
    @Override
    public int deleteSysFeedingRecordsByIds(Long[] ids)
    {
        return sysFeedingRecordsMapper.deleteSysFeedingRecordsByIds(ids);
    }

    /**
     * 删除投喂记录信息
     * 
     * @param id 投喂记录主键
     * @return 结果
     */
    @Override
    public int deleteSysFeedingRecordsById(Long id)
    {
        return sysFeedingRecordsMapper.deleteSysFeedingRecordsById(id);
    }
}
